<template>
  <div class="assessment-container">
    <div>
      <!-- 返回按钮 -->

      <div class="navbar">
        <div class="nav-back" @click="$router.go(-1)">
          <i class="fas fa-chevron-left"></i>
        </div>
        <div class="nav-title">焦虑自评量表</div>
        <div class="nav-placeholder"></div>
      </div>

      <!-- 进度条 -->
      <div class="progress-bar">
        <div
          class="progress"
          :style="{
            width: `${((currentIndex + 1) / subjectList.length) * 100}%`,
          }"
        ></div>
      </div>

      <!-- 进度文字 -->
      <div class="progress-text">
        第 {{ currentIndex + 1 }} 题 / 共 {{ subjectList.length }} 题
      </div>

      <!-- 题目区域 -->
      <div class="question-container">
        <h2 class="question-title">{{ currentQuestion.subject }}</h2>

        <!-- 选项区域 -->
        <div class="options-container">
          <div
            v-for="option in currentQuestion.item"
            :key="option.id"
            class="option-item"
            :class="{ selected: selectedOptions[currentIndex] === option.id }"
            @click="selectOption(option.id)"
          >
            <span class="option-radio"></span>
            <span class="option-text">{{ option.name }}</span>
          </div>
        </div>
      </div>

      <!-- 按钮区域 -->
      <div class="button-container">
        <button
          class="btn btn-prev"
          :disabled="currentIndex === 0 || isSubmitting"
          @click="prevQuestion"
        >
          上一题
        </button>

        <button
          v-if="currentIndex < subjectList.length - 1"
          class="btn btn-next"
          :disabled="!selectedOptions[currentIndex] || isSubmitting"
          @click="nextQuestion"
        >
          下一题
        </button>

        <button
          v-else
          class="btn btn-submit"
          :disabled="!selectedOptions[currentIndex] || isSubmitting"
          @click="submitAnswer"
        >
          <span v-if="isSubmitting" class="btn-loading">
            <span class="loading-spinner"></span>
            提交中...
          </span>
          <span v-else>提交答案</span>
        </button>
      </div>

      <!-- 提交成功提示 -->
      <div v-if="submitSuccess" class="success-message">
        <div class="success-content">
          <div class="success-icon">✓</div>
          <h3>提交成功！</h3>
          <p>正在跳转至报告...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getLbassessment, lbAnswerSave, practiceCheckin } from "../../api/user";

export default {
  name: "AssessmentPage",
  data() {
    return {
      subjectList: [], // 题目列表
      currentIndex: 0, // 当前题目索引
      selectedOptions: [], // 用户选择的选项ID数组
      assId: null, // 评估ID
      isSubmitting: false, // 是否正在提交
      submitSuccess: false, // 是否提交成功
    };
  },
  computed: {
    // 当前题目
    currentQuestion() {
      return this.subjectList[this.currentIndex] || {};
    },
  },
  created() {
    // 从路由参数获取评估ID
    this.task = JSON.parse(this.$route.query.task);
    this.assId = JSON.parse(this.$route.query.task).info;
    this.fetchQuestions();
  },
  methods: {
    completeTraining() {
      let data = {
        personalPracticeId: this.task.id,
        practiceTime: this.task.practiceTime,
        userId: localStorage.getItem("userId"),
      };
      practiceCheckin(data)
        .then((res) => {})
        .catch((error) => {});
    },

    // 返回上一页
    goBack() {
      // 使用路由返回上一页，如果无法返回则返回到首页
      if (window.history.length > 1) {
        this.$router.go(-1);
      } else {
        this.$router.push("/"); // 如果没有历史记录，则返回到首页，你可以根据需要修改这个路径
      }
    },

    // 获取题目
    fetchQuestions() {
      let data = { assId: this.assId };
      getLbassessment(data)
        .then((res) => {
          if (res.code === 200) {
            this.subjectList = res.data;
            // 初始化答案数组
            this.selectedOptions = new Array(this.subjectList.length).fill(
              null
            );
          } else {
            console.error("获取题目失败:", res.message);
            alert("获取题目失败，请重试");
          }
        })
        .catch((error) => {
          console.error("请求题目出错:", error);
          alert("获取题目失败，请检查网络连接");
        });
    },

    // 选择选项
    selectOption(optionId) {
      this.$set(this.selectedOptions, this.currentIndex, optionId);

      // 如果不是最后一题，自动进入下一题
      if (this.currentIndex < this.subjectList.length - 1) {
        setTimeout(() => {
          this.nextQuestion();
        }, 300);
      }
    },

    // 上一题
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
      }
    },

    // 下一题
    nextQuestion() {
      if (
        this.currentIndex < this.subjectList.length - 1 &&
        this.selectedOptions[this.currentIndex]
      ) {
        this.currentIndex++;
      }
    },

    // 提交答案
    submitAnswer() {
      // 检查是否所有题目都已作答
      if (this.selectedOptions.some((option) => option === null)) {
        alert("请完成所有题目后再提交");
        return;
      }

      this.isSubmitting = true;

      let data = {
        userId: localStorage.getItem("userId"),
        unitId: localStorage.getItem("unitId"),
        assId: this.assId,
        data: this.selectedOptions,
      };

      lbAnswerSave(data)
        .then((res) => {
          if (res.code == 200) {
            this.completeTraining();
            this.submitSuccess = true;
            // 延迟跳转，让用户看到成功提示
            setTimeout(() => {
              this.$router.push({
                name: "员工端-打卡报告",
                query: { id: res.data },
              });
            }, 1500);
          } else {
            alert("提交失败：" + res.message);
          }
        })
        .catch((error) => {
          console.error("提交答案出错:", error);
          alert("提交失败，请重试");
        })
        .finally(() => {
          this.isSubmitting = false;
        });
    },
  },
};
</script>

<style scoped>
.assessment-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  background-color: #f8fbff;
  min-height: 100vh;
  position: relative;
}

/* 导航栏 */
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  /* background: white; */
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  z-index: 1000;
  /* box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); */
}

.nav-back {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #eef0ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #5b67ff;
  border: none;
  cursor: pointer;
}

.nav-back:hover {
  background: #eef0ff;
}

.nav-title {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.nav-placeholder {
  width: 40px;
}

.progress-bar {
  margin-top: 50px;
  height: 8px;
  background-color: #e1ecff;
  border-radius: 4px;
  margin-bottom: 15px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #4dabf7, #339af0);
  transition: width 0.4s ease;
  border-radius: 4px;
}

.progress-text {
  text-align: center;
  color: #5c7cfa;
  margin-bottom: 30px;
  font-size: 16px;
  font-weight: 500;
}

.question-container {
  background-color: #fff;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 15px rgba(77, 171, 247, 0.15);
  margin-bottom: 30px;
  border: 1px solid #e7f5ff;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.question-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(77, 171, 247, 0.2);
}

.question-title {
  font-size: 20px;
  line-height: 1.6;
  margin-bottom: 25px;
  color: #1a3b5d;
  font-weight: 600;
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 18px 20px;
  border: 2px solid #e9ecef;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fff;
}

.option-item:hover {
  background-color: #f1f9ff;
  border-color: #a5d8ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(77, 171, 247, 0.15);
}

.option-item.selected {
  border-color: #4dabf7;
  background-color: #e7f5ff;
  box-shadow: 0 4px 12px rgba(77, 171, 247, 0.2);
}

.option-radio {
  width: 22px;
  height: 22px;
  border: 2px solid #adb5bd;
  border-radius: 50%;
  margin-right: 15px;
  position: relative;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.option-item.selected .option-radio {
  border-color: #4dabf7;
  background-color: #4dabf7;
}

.option-item.selected .option-radio::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 10px;
  height: 10px;
  background-color: white;
  border-radius: 50%;
}

.option-text {
  font-size: 17px;
  color: #343a40;
  font-weight: 500;
}

.button-container {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.btn {
  padding: 14px 28px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 600;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.btn:disabled {
  background-color: #e9ecef;
  color: #adb5bd;
  cursor: not-allowed;
  box-shadow: none;
  transform: none !important;
}

.btn:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

.btn:not(:disabled):active {
  transform: translateY(0);
}

.btn-prev {
  background-color: #f8f9fa;
  color: #495057;
  border: 1px solid #dee2e6;
}

.btn-prev:not(:disabled):hover {
  background-color: #e9ecef;
}

.btn-next,
.btn-submit {
  background: linear-gradient(135deg, #4dabf7, #339af0);
  color: white;
}

.btn-next:not(:disabled):hover,
.btn-submit:not(:disabled):hover {
  background: linear-gradient(135deg, #339af0, #228be6);
  box-shadow: 0 4px 12px rgba(51, 154, 240, 0.4);
}

.btn-loading {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 8px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 提交成功提示 */
.success-message {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.success-content {
  background: white;
  padding: 40px;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  animation: scaleIn 0.4s ease;
  max-width: 90%;
  width: 300px;
}

.success-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #51cf66, #40c057);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  color: white;
  font-size: 30px;
  font-weight: bold;
}

.success-content h3 {
  color: #2b8a3e;
  margin-bottom: 10px;
  font-size: 24px;
}

.success-content p {
  color: #5c7cfa;
  font-size: 16px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes scaleIn {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

@media (max-width: 600px) {
  .assessment-container {
    padding: 15px;
  }

  .btn-back {
    padding: 8px 12px;
    font-size: 13px;
  }

  .question-container {
    padding: 20px;
  }

  .button-container {
    flex-direction: column;
    gap: 12px;
  }

  .btn {
    width: 100%;
  }

  .question-title {
    font-size: 18px;
  }

  .option-text {
    font-size: 16px;
  }
}
</style>
